package com.dengpp.pdform.holder;

import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.dengpp.pdform.R;
import com.dengpp.pdform.adapter.AttributeAdapter;
import com.dengpp.pdform.base.BaseAttributeViewHolder;
import com.dengpp.pdform.config.AttributeConfig;
import com.dengpp.pdform.model.CascadingOption;

import java.util.ArrayList;
import java.util.List;


public class CascadingDropdownViewHolder extends BaseAttributeViewHolder {
    private TextView tvTitle;
    private TextView tvSelectedPath;
    private LinearLayout layoutEdit;
    private Spinner spinnerLevel1, spinnerLevel2, spinnerLevel3;
    private TextView tvValue;

    private List<CascadingOption> allLevel1Options;
    private List<CascadingOption> currentLevel2Options;
    private List<CascadingOption> currentLevel3Options;

    private String selectedLevel1, selectedLevel2, selectedLevel3;
    private AttributeConfig currentAttribute;
    private boolean isSettingSpinner = false;
    private AttributeAdapter.OnAttributeChangeListener currentListener;

    public CascadingDropdownViewHolder(@NonNull View itemView) {
        super(itemView);
        tvTitle = itemView.findViewById(R.id.tv_title);
        tvSelectedPath = itemView.findViewById(R.id.tv_selected_path);
        layoutEdit = itemView.findViewById(R.id.layout_edit);
        spinnerLevel1 = itemView.findViewById(R.id.spinner_level1);
        spinnerLevel2 = itemView.findViewById(R.id.spinner_level2);
        spinnerLevel3 = itemView.findViewById(R.id.spinner_level3);
        tvValue = itemView.findViewById(R.id.tv_value);
    }

    @Override
    public void bind(AttributeConfig attribute, boolean isEditMode, AttributeAdapter.OnAttributeChangeListener listener) {
        this.currentAttribute = attribute;
        this.currentListener = listener;

        // 移除旧的监听器
        spinnerLevel1.setOnItemSelectedListener(null);
        spinnerLevel2.setOnItemSelectedListener(null);
        spinnerLevel3.setOnItemSelectedListener(null);

        // 使用带星号的标题
        tvTitle.setText(getTitleWithRequiredStar(attribute.getTitle(), attribute.isRequired()));

        // 初始化数据
        allLevel1Options = attribute.getCascadingOptions();
        if (allLevel1Options == null) {
            allLevel1Options = new ArrayList<>();
        }

        // 恢复选中的值
        restoreSelectedValues(attribute);

        if (isEditMode && attribute.isEditable()) {
            layoutEdit.setVisibility(View.VISIBLE);
            tvValue.setVisibility(View.GONE);

            // 设置所有Spinner
            initializeSpinners(attribute, listener);

            // 更新显示
            updateSelectedPathDisplay();
        } else {
            layoutEdit.setVisibility(View.GONE);
            tvValue.setVisibility(View.VISIBLE);

            String displayText = getSelectedValuesDisplay();
            tvValue.setText(displayText.isEmpty() ? "未选择" : displayText);
        }
    }

    private void restoreSelectedValues(AttributeConfig attribute) {
        selectedLevel1 = attribute.getCascadingValueAt(0);
        selectedLevel2 = attribute.getCascadingValueAt(1);
        selectedLevel3 = attribute.getCascadingValueAt(2);
    }

    private void initializeSpinners(AttributeConfig attribute, AttributeAdapter.OnAttributeChangeListener listener) {
        // 设置第一级Spinner
        setupLevel1Spinner(attribute, listener);

        // 如果第一级有选中值，设置第二级Spinner
        if (selectedLevel1 != null) {
            updateLevel2Options(selectedLevel1);
            setupLevel2Spinner(attribute, listener);

            // 如果第二级有选中值，设置第三级Spinner
            if (selectedLevel2 != null) {
                updateLevel3Options(selectedLevel2);
                setupLevel3Spinner(attribute, listener);
            } else {
                setupEmptySpinner(spinnerLevel3, "请选择区县");
            }
        } else {
            setupEmptySpinner(spinnerLevel2, "请先选择省份");
            setupEmptySpinner(spinnerLevel3, "请先选择城市");
        }
    }

    private void setupLevel1Spinner(AttributeConfig attribute, AttributeAdapter.OnAttributeChangeListener listener) {
        List<String> level1Labels = getOptionLabels(allLevel1Options, "请选择省份");
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                itemView.getContext(),
                R.layout.library_spinner_item,
                level1Labels
        );
        adapter.setDropDownViewResource(R.layout.library_spinner_dropdown_item);
        spinnerLevel1.setAdapter(adapter);

        // 设置选中项
        int position = getSelectedPosition(allLevel1Options, selectedLevel1);
        setSpinnerSelection(spinnerLevel1, position);

        spinnerLevel1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isSettingSpinner) return;

                if (position > 0) {
                    String newValue = allLevel1Options.get(position - 1).getValue();
                    if (!newValue.equals(selectedLevel1)) {
                        handleLevel1Selection(newValue, attribute, listener);
                    }
                } else if (selectedLevel1 != null) {
                    handleLevel1Selection(null, attribute, listener);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }

    private void handleLevel1Selection(String newValue, AttributeConfig attribute, AttributeAdapter.OnAttributeChangeListener listener) {
        selectedLevel1 = newValue;
        attribute.updateCascadingSelection(0, selectedLevel1);

        if (selectedLevel1 != null) {
            updateLevel2Options(selectedLevel1);
            setupLevel2Spinner(attribute, listener);
        } else {
            selectedLevel2 = selectedLevel3 = null;
            attribute.updateCascadingSelection(1, null);
            attribute.updateCascadingSelection(2, null);
            setupEmptySpinner(spinnerLevel2, "请先选择省份");
            setupEmptySpinner(spinnerLevel3, "请先选择城市");
        }

        updateSelectedPathDisplay();
        notifyValueChanged(attribute, listener);
    }

    private void setupLevel2Spinner(AttributeConfig attribute, AttributeAdapter.OnAttributeChangeListener listener) {
        List<String> level2Labels = getOptionLabels(currentLevel2Options,
                currentLevel2Options.isEmpty() ? "暂无选项" : "请选择城市");

        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                itemView.getContext(),
                R.layout.library_spinner_item,
                level2Labels
        );
        adapter.setDropDownViewResource(R.layout.library_spinner_dropdown_item);
        spinnerLevel2.setAdapter(adapter);

        int position = getSelectedPosition(currentLevel2Options, selectedLevel2);
        setSpinnerSelection(spinnerLevel2, position);

        spinnerLevel2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isSettingSpinner) return;

                if (position > 0 && !currentLevel2Options.isEmpty()) {
                    String newValue = currentLevel2Options.get(position - 1).getValue();
                    if (!newValue.equals(selectedLevel2)) {
                        handleLevel2Selection(newValue, attribute, listener);
                    }
                } else if (selectedLevel2 != null) {
                    handleLevel2Selection(null, attribute, listener);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }

    private void handleLevel2Selection(String newValue, AttributeConfig attribute, AttributeAdapter.OnAttributeChangeListener listener) {
        selectedLevel2 = newValue;
        attribute.updateCascadingSelection(1, selectedLevel2);

        if (selectedLevel2 != null) {
            updateLevel3Options(selectedLevel2);
            setupLevel3Spinner(attribute, listener);
        } else {
            selectedLevel3 = null;
            attribute.updateCascadingSelection(2, null);
            setupEmptySpinner(spinnerLevel3, "请先选择城市");
        }

        updateSelectedPathDisplay();
        notifyValueChanged(attribute, listener);
    }

    private void setupLevel3Spinner(AttributeConfig attribute, AttributeAdapter.OnAttributeChangeListener listener) {
        List<String> level3Labels = getOptionLabels(currentLevel3Options,
                currentLevel3Options.isEmpty() ? "暂无选项" : "请选择区县");

        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                itemView.getContext(),
                R.layout.library_spinner_item,
                level3Labels
        );
        adapter.setDropDownViewResource(R.layout.library_spinner_dropdown_item);
        spinnerLevel3.setAdapter(adapter);

        int position = getSelectedPosition(currentLevel3Options, selectedLevel3);
        setSpinnerSelection(spinnerLevel3, position);

        spinnerLevel3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isSettingSpinner) return;

                if (position > 0 && !currentLevel3Options.isEmpty()) {
                    String newValue = currentLevel3Options.get(position - 1).getValue();
                    if (!newValue.equals(selectedLevel3)) {
                        selectedLevel3 = newValue;
                        attribute.updateCascadingSelection(2, selectedLevel3);
                        updateSelectedPathDisplay();
                        notifyValueChanged(attribute, listener);
                    }
                } else if (selectedLevel3 != null) {
                    selectedLevel3 = null;
                    attribute.updateCascadingSelection(2, null);
                    updateSelectedPathDisplay();
                    notifyValueChanged(attribute, listener);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }

    private void updateLevel2Options(String level1Value) {
        currentLevel2Options = new ArrayList<>();
        for (CascadingOption option : allLevel1Options) {
            if (option.getValue().equals(level1Value) && option.getChildren() != null) {
                currentLevel2Options = option.getChildren();
                break;
            }
        }

        // 如果第二级只有一个选项，自动选中它
        if (currentLevel2Options.size() == 1 && selectedLevel2 == null) {
            selectedLevel2 = currentLevel2Options.get(0).getValue();
            if (currentAttribute != null && currentListener != null) {
                currentAttribute.updateCascadingSelection(1, selectedLevel2);
                updateLevel3Options(selectedLevel2);
            }
        }
    }

    private void updateLevel3Options(String level2Value) {
        currentLevel3Options = new ArrayList<>();
        for (CascadingOption option : currentLevel2Options) {
            if (option.getValue().equals(level2Value) && option.getChildren() != null) {
                currentLevel3Options = option.getChildren();
                break;
            }
        }

        // 如果第三级只有一个选项，自动选中它
        if (currentLevel3Options.size() == 1 && selectedLevel3 == null) {
            selectedLevel3 = currentLevel3Options.get(0).getValue();
            if (currentAttribute != null && currentListener != null) {
                currentAttribute.updateCascadingSelection(2, selectedLevel3);
            }
        }
    }

    private List<String> getOptionLabels(List<CascadingOption> options, String hint) {
        List<String> labels = new ArrayList<>();
        labels.add(hint);
        if (options != null) {
            for (CascadingOption option : options) {
                labels.add(option.getLabel());
            }
        }
        return labels;
    }

    private int getSelectedPosition(List<CascadingOption> options, String selectedValue) {
        if (selectedValue == null || options == null) return 0;
        for (int i = 0; i < options.size(); i++) {
            if (options.get(i).getValue().equals(selectedValue)) {
                return i + 1;
            }
        }
        return 0;
    }

    private void setSpinnerSelection(Spinner spinner, int position) {
        isSettingSpinner = true;
        spinner.setSelection(position, false);
        isSettingSpinner = false;
    }

    private void setupEmptySpinner(Spinner spinner, String hint) {
        List<String> emptyList = new ArrayList<>();
        emptyList.add(hint);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                itemView.getContext(),
                R.layout.library_spinner_item,
                emptyList
        );
        adapter.setDropDownViewResource(R.layout.library_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        setSpinnerSelection(spinner, 0);
    }

    private void updateSelectedPathDisplay() {
        String displayText = getSelectedValuesDisplay();
        if (!displayText.isEmpty()) {
            tvSelectedPath.setVisibility(View.VISIBLE);
            tvSelectedPath.setText(displayText);
        } else {
            tvSelectedPath.setVisibility(View.GONE);
        }
    }

    private String getSelectedValuesDisplay() {
        StringBuilder sb = new StringBuilder();
        if (selectedLevel1 != null) {
            String label = getLabelByValue(allLevel1Options, selectedLevel1);
            sb.append(label != null ? label : selectedLevel1);
        }
        if (selectedLevel2 != null) {
            String label = getLabelByValue(currentLevel2Options, selectedLevel2);
            sb.append(" / ").append(label != null ? label : selectedLevel2);
        }
        if (selectedLevel3 != null) {
            String label = getLabelByValue(currentLevel3Options, selectedLevel3);
            sb.append(" / ").append(label != null ? label : selectedLevel3);
        }
        return sb.toString();
    }

    private String getLabelByValue(List<CascadingOption> options, String value) {
        if (options == null || value == null) return null;
        for (CascadingOption option : options) {
            if (option.getValue().equals(value)) {
                return option.getLabel();
            }
        }
        return null;
    }

    private void notifyValueChanged(AttributeConfig attribute, AttributeAdapter.OnAttributeChangeListener listener) {
        if (listener != null) {
            List<String> selectedValues = new ArrayList<>();
            if (selectedLevel1 != null) selectedValues.add(selectedLevel1);
            if (selectedLevel2 != null) selectedValues.add(selectedLevel2);
            if (selectedLevel3 != null) selectedValues.add(selectedLevel3);

            listener.onAttributeChanged(attribute.getKey(), selectedValues);
        }
    }

    @Override
    public void onViewRecycled() {
        super.onViewRecycled();
        spinnerLevel1.setOnItemSelectedListener(null);
        spinnerLevel2.setOnItemSelectedListener(null);
        spinnerLevel3.setOnItemSelectedListener(null);
        currentAttribute = null;
        currentListener = null;
        isSettingSpinner = false;
    }
}
